package com.cxy.ch1.threadlocal;

/**
 * @ClassName: UseThreadLocal
 * @Description: TODO(使用ThreadLocal的类)
 * @author 菜徐鸭
 * @date 2020年4月13日
 *
 */
/**
 * 类说明：演示ThreadLocal的使用
 */
public class UseThreadLocal {

	private static ThreadLocal<Integer> intLocal = new ThreadLocal<Integer>() {
		@Override
		protected Integer initialValue() {
			return 1;
		}
	};

	private static ThreadLocal<String> stringThreadLocal;

	/**
	 * 运行3个线程
	 */
	public void StartThreadArray() {
		Thread[] runs = new Thread[3];
		for (int i = 0; i < runs.length; i++) {
			runs[i] = new Thread(new TestThread(i));
		}
		for (int i = 0; i < runs.length; i++) {
			runs[i].start();
		}
	}

	/**
	 * 类说明：测试线程，线程的工作是将ThreadLocal变量的值变化，并写回，看看线程之间是否会互相影响
	 */
	public static class TestThread implements Runnable {
		int id;

		public TestThread(int id) {
			this.id = id;
		}

		public void run() {
			System.out.println(Thread.currentThread().getName() + ":线程start");
			Integer s = intLocal.get();
			s = s + id;
			intLocal.set(s);
			System.out.println(Thread.currentThread().getName() + ": intLocal值=" + intLocal.get());
			// intLocal.remove();
		}
	}

	/**
	 * 为每个线程都有变量的副本，线程之间的隔离，Spring在使用事务的时候就是用的ThreadLocal(如数据库连接)
	 * Thread不保证变量的同步，只保证变量的隔离
	 * @param args
	 */
	public static void main(String[] args) {
		UseThreadLocal test = new UseThreadLocal();
		test.StartThreadArray();
	}
}